package behavior.iterator.impl;

import java.util.Arrays;

import behavior.iterator.Collection;
import behavior.iterator.Iterator;

/**
 * 应该有一个List的接口的，这里只是一个demo，暂时省去中间环节
 * 
 * @author thinkpad
 *
 */
public class ArrayList implements Collection {

	private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

	transient Object[] elementData;

	private int size;

	public ArrayList() {
		elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
	}

	@Override
	public Iterator iterator() {
		return new Itr();
	}

	@Override
	public boolean add(Object obj) {
		//这种扩容方式不好，可以参考真正的ArrayList是怎么扩容的，这里只是快速模拟扩容
		elementData = Arrays.copyOf(elementData, size + 1);
		elementData[size] = obj;
		size++;
		return true;
	}

	@Override
	public Object remove(int index) {
		Object oldValue = elementData[index];

		int numMoved = size - index - 1;
		if (numMoved > 0)
			System.arraycopy(elementData, index + 1, elementData, index, numMoved);
		elementData[--size] = null;

		return oldValue;
	}

	@Override
	public int size() {
		return size;
	}

	private class Itr implements Iterator {

		int cursor = -1;

		public Object next() {
			return elementData[++cursor];
		}

		@Override
		public boolean hasNext() {
			return cursor < size - 1;
		}

	}
}
